package com.juzi.wopu.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.juzi.wopu.dao.BaseDao;
import com.juzi.wopu.query.BaseQuery;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.service.IBaseService;

public abstract class BaseServiceImpl<T> implements IBaseService<T>{

	private  Class<T> entityClass;
	protected BaseDao<T> BaseDao;
	
	@SuppressWarnings("all")
	public BaseServiceImpl(){
		Class clazz=getClass();
		Type type = clazz.getGenericSuperclass();
		if(type instanceof ParameterizedType){
			ParameterizedType parameterizedType=(ParameterizedType)type;
			entityClass = (Class) parameterizedType.getActualTypeArguments()[0];
		}
	}
	
	public void setBaseDao(BaseDao<T> baseDao) {
		BaseDao = baseDao;
	}
	
	@Override
	public void save(T t) {
		BaseDao.save(t);
	}

	@Override
	public void update(T t) {
		BaseDao.update(t);
	}

	@Override
	public void delete(Long id) {
		BaseDao.delete(entityClass, id);
	}

	@Override
	public T get(Long id) {
		return BaseDao.get(entityClass, id);
	}

	@Override
	public List<T> getAll() {
		return BaseDao.getAll(entityClass);
	}

	@Override
	public PageList findByQuery(BaseQuery baseQuery) {
		return BaseDao.findByQuery(baseQuery);
	}

	@SuppressWarnings("resource")
	@Override
	public List<String[]> importExcls(File upload) throws Exception {
		List<String[]> data=new ArrayList<String[]>();
		
		FileInputStream fin=new FileInputStream(upload);
		Workbook wb=new XSSFWorkbook(fin);
		
		Sheet sheet = wb.getSheetAt(0);
		for(int rownum = 0;rownum<sheet.getLastRowNum();rownum++){
			Row row = sheet.getRow(rownum+1);
			String[] strings=new String[row.getLastCellNum()];
			for(int cellnum=0;cellnum<row.getLastCellNum();cellnum++){
				Cell cell = row.getCell(cellnum);
				if(cell !=null){
					strings[cellnum]=cell.getStringCellValue();
				}
			}
			data.add(strings);
		}
		return data;
	}
}
